//
//  UILabel+text.m
//  ThinkDrive_For_iPhone
//
//  Created by LZP on 2018/7/27.
//  Copyright © 2018年 Richinfo. All rights reserved.
//

#import "UILabel+text.h"

@implementation UILabel (text)

///根据宽度计算文字的高度
- (CGFloat)textheight:(NSString *)string {
    NSString *text = string;
    UIFont *font = self.font;//跟label的字体大小一样
    CGSize size = CGSizeMake(self.frame.size.width, MAXFLOAT);//跟label的宽设置一样
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    size = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return size.height;
}

///根据高度计算文字的宽度
- (CGFloat)textWidth:(NSString *)string {
    NSString *text = string;
    UIFont *font = self.font;//跟label的字体大小一样
    CGSize size = CGSizeMake(MAXFLOAT, self.frame.size.height);//跟label的宽设置一样
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    size = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:dic context:nil].size;
    return size.width;
}

- (void)changeAlignmentRightandLeft{
    
    CGRect textSize = [self.text boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : self.font} context:nil];
    
    CGFloat margin = (self.frame.size.width - textSize.size.width) / (self.text.length - 1);
    
    NSNumber *number = [NSNumber numberWithFloat:margin];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:self.text];
    [attributeString addAttribute:(id)kCTKernAttributeName value:number range:NSMakeRange(0, self.text.length - 1)];
    self.attributedText = attributeString;
    
}
@end
